import parseAttrsString from './parseAttrsString';

export default function (templateStr) {
  // 指针
  let index = 0;

  // 剩余字符
  let rest = templateStr;

  // 开始标记
  let startRegexp = /^\<([a-z]+[1-6]?)(\s[^\<]+)?\>/;
  // 结束标记
  let endRegexp = /^\<\/([a-z]+[1-6]?)\>/;
  // 检测文字
  let wordRegexp = /^([^\<]+)\<\/([a-z]+[1-6]?)\>/;

  // 栈1，存储标签
  let stack1 = [];
  // 栈2，存储数组
  let stack2 = [{ children: [] }];

  while (index < templateStr.length - 1) {
    rest = templateStr.substring(index);
    if (startRegexp.test(rest)) {
      // 检测开始标记
      let tag = rest.match(startRegexp)[1];
      let attrsString = rest.match(startRegexp)[2];
      let attrsStringLength = attrsString ? attrsString.length : 0;
      // console.log('开始的标记', tag);
      stack1.push(tag);
      stack2.push({ tag, children: [], attrs: parseAttrsString(attrsString) });
      // 跳过匹配到的长度
      index += (tag.length + 2 + attrsStringLength);
    } else if (endRegexp.test(rest)) {
      // 检测结束标签
      let tag = rest.match(endRegexp)[1];
      // console.log('结束的标记', tag);
      // 栈1和栈2一定是相对应的
      let pop_tag = stack1.pop();
      if (tag == pop_tag) {
        let pop_arr = stack2.pop();
        if (stack2.length > 0) {
          stack2[stack2.length - 1].children.push(pop_arr);
        }
      } else {
        throw new Error(stack1[stack1.length - 1] + '标签没封闭');
      }
      index += (tag.length + 3);
    } else if (wordRegexp.test(rest)) {
      // 检测文字
      let word = rest.match(wordRegexp)[1];
      // 检测是不是全是空
      if (!/^\s+$/.test(word)) {
        // console.log('检测到文字', word);
        stack2[stack2.length - 1].children.push({ text: word, type: 3 });
      }
      index += word.length;
    } else {
      index++;
    }
  }
  return stack2[0].children[0];
}